package com.example.product_practices.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.product_practices.domain.User;
import com.example.product_practices.mapper.ReplyTbMapper;
import com.example.product_practices.utils.HttpUtils;
import com.example.product_practices.vo.SociUserinfo;
import com.example.product_practices.vo.SocialUser;
import com.example.product_practices.vo.UserLoginVo;
import com.example.product_practices.vo.UserRegister;
import com.example.product_practices.exception.PhoneException;
import com.example.product_practices.exception.UsernameException;
import com.example.product_practices.mapper.UserMapper;
import com.example.product_practices.service.IUserService;
import com.example.product_practices.utils.BCryptPasswordEncoder;
//import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import xin.altitude.cms.common.entity.AjaxResult;

import java.util.Date;
import java.util.HashMap;

import java.util.List;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Override
    public User oauthlogin(SocialUser socialUser) throws Exception {
        //            https://gitee.com/api/v5/user?access_token=c92c014432552f232903002eb5a4d5d7
        HashMap<String,String> map2 = new HashMap<>();
        map2.put("access_token",socialUser.getAccess_token());
        HttpResponse get = HttpUtils.doGet("https://gitee.com", "/api/v5/user", "get",
                new HashMap<>(), map2);
        if (get.getStatusLine().getStatusCode()==200){
            String string1 = EntityUtils.toString(get.getEntity());
            SociUserinfo sociUserinfo = JSON.parseObject(string1, SociUserinfo.class);
            String userId = String.valueOf(sociUserinfo.getId());
            User social_uid = this.baseMapper.selectOne(new QueryWrapper<User>().eq("social_uid", userId));
            if (social_uid !=null) {
                User memberEntity = new User();
                memberEntity.setId(social_uid.getId());
                memberEntity.setAccessToken(socialUser.getAccess_token());
                memberEntity.setExpiresIn(socialUser.getExpires_in());
                this.baseMapper.updateById(memberEntity);
                social_uid.setAccessToken(socialUser.getAccess_token());
                social_uid.setExpiresIn(socialUser.getExpires_in());
                return  social_uid;
            }else {
                User regist = new User();
                //TODO
                regist.setName(sociUserinfo.getName());
                regist.setCreateTime(new Date());
                regist.setSocialUid(String.valueOf(sociUserinfo.getId()));
                regist.setAccessToken(socialUser.getAccess_token());
                regist.setExpiresIn(socialUser.getExpires_in());
                this.baseMapper.insert(regist);
                return regist;
            }
        }else {
            return null;
        }
    }

    @Override
    public void regist(UserRegister userRegister) {
        User user = new User();

        //设置其它的默认信息
        //检查用户名和手机号是否唯一。感知异常，异常机制
        checkPhoneUnique(userRegister.getPhone());
        checkUserNameUnique(userRegister.getUserName());

        user.setUsername(userRegister.getUserName());
        //密码进行MD5加密
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        String encode = bCryptPasswordEncoder.encode(userRegister.getPassword());
        user.setPassword(encode);
        user.setPhone(userRegister.getPhone());
        //TODO
        user.setCreateTime(new Date());
        System.err.println("true =创建成功 " + true);
        this.baseMapper.insert(user);
    }

    @Override
    public User login(UserLoginVo userLoginVo) {
        String loginacct = userLoginVo.getLoginacct();
        String password = userLoginVo.getPassword();
        User user = this.baseMapper.selectOne(new QueryWrapper<User>().eq("username", loginacct)
                .or().eq("phone", loginacct));
        if (user == null) {
            return null;
        } else {
            String password1 = user.getPassword();
            BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
            boolean matches = bCryptPasswordEncoder.matches(password, password1);
            if (matches) {
                return user;
            }

        }
        return null;
    }

    @Override
    public void checkPhoneUnique(String phone) throws PhoneException {

        if (this.baseMapper.selectCount(new QueryWrapper<User>().eq("phone", phone)) > 0) {
            throw new PhoneException();
        }

    }

    @Override
    public void checkUserNameUnique(String userName) throws UsernameException {

        if (this.baseMapper.selectCount(new QueryWrapper<User>().eq("username", userName)) > 0) {
            throw new UsernameException();
        }
    }


    @Autowired
    UserMapper userMapper;

    public List<User> getRenterUnderManager(int current,int size){
        int loc = (current-1)*size;
        return userMapper.getRenterPage(loc,size);
    }

    public List<User> getAllRenter(){
        return userMapper.getAllRenter();
    }


    public int getId(String name) {
        return userMapper.getId(name);
    }
}
